package com.shuo.map;

import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap的节点Entry有key,value,left,right,parent,color等属性
 *
 * 0. 唯一用途: 按自然顺序或自定义顺序遍历key
 * 1. 底层结构就是红黑树(没有数组没有链表)，时间复杂度保证为log(n)
 * 2. key不能为null，为null为抛出NullPointException的
 * 3. 默认对key自然排序, 想要自定义比较, 在构造方法中传入Comparator对象
 * 4. TreeMap非同步的，想要同步可以使用Collections来进行封
 */
public class TreeMapTest {
    private static class Student {
        private int age;
        private String name;

        public Student(String name, int age) {
            this.age = age;
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        // 初始化Comparator
        TreeMap<Student, String> map = new TreeMap<>((o1, o2) -> {
            int num = o1.getAge() - o2.getAge();
            int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
            return num2;
        });
        Student s1 = new Student("潘安", 30);
        Student s2 = new Student("柳下惠", 35);
        map.put(s1, "宋朝");
        map.put(s2, "元朝");
        // map.put(null, "汉朝");
        /* 遍历 */
        Set<Student> set = map.keySet();
        for (Student student : set) {
            String value = map.get(student);
            System.out.println(student + "---------" + value);
        }
    }
}
